package cn.chengpengper.shortlink.component;

import cn.chengpengper.shortlink.config.OSSConfig;
import cn.chengpengper.shortlink.constant.DateFormatterTemplate;
import cn.chengpengper.shortlink.constant.ShortLinkConstant;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.UUID;

/**
 * This class is used to upload files to Alibaba Cloud OSS.
 * Basic configuration information is obtained from {@link OSSConfig}.
 *
 * @author huchengpeng
 * @version v1.0.0
 * @date 2023/8/21 23:03
 * @description OSS 服务组件
 */
@Slf4j
@Component
public class OssComponent {

    @Autowired
    private OSSConfig ossConfig;

    @Value("${spring.application.name}")
    private String appName;

    public String upload(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndPoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

        String filename = getFileName(file);
        try {
            PutObjectResult result = ossClient.putObject(ossConfig.getBucketName(), filename, file.getInputStream());
            log.info("OssComponent | upload | Result is {}", result);
            if (Objects.nonNull(result)) {
                return String.format("https://%s.%s/%s", ossConfig.getBucketName(), ossConfig.getEndPoint(), filename);
            }
        } catch (IOException e) {
            log.error("OssComponent | upload | Has a exception:", e);
        } finally {
            ossClient.shutdown();
        }
        return null;
    }

    private String getFileName(MultipartFile file) {
        String originalFilename = StringUtils.isNotBlank(file.getOriginalFilename()) ? file.getOriginalFilename() : file.getName();
        String extension = originalFilename.substring(originalFilename.lastIndexOf(ShortLinkConstant.DOT));

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(DateFormatterTemplate.YMD);

        String uuid = UUID.randomUUID().toString().replace(ShortLinkConstant.LINE, ShortLinkConstant.BLANK);
        return String.join(ShortLinkConstant.SPLIT, appName, pattern.format(now), uuid + extension);
    }
}
